package com.ztf0337.mycurriculumdesign.ui.activity;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textview.MaterialTextView;
import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.Utils.AccountUtils;
import com.ztf0337.mycurriculumdesign.Utils.Checker;
import com.ztf0337.mycurriculumdesign.Utils.GetUtils;
import com.ztf0337.mycurriculumdesign.Utils.TextDate;
import com.ztf0337.mycurriculumdesign.Utils.TimeConverters;
import com.ztf0337.mycurriculumdesign.Utils.TransitionUtils;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.RentedParkingSpace;
import com.ztf0337.mycurriculumdesign.service.OrderService;
import com.ztf0337.mycurriculumdesign.service.ParkLotService;
import com.ztf0337.mycurriculumdesign.service.ParkingSpaceService;
import com.ztf0337.mycurriculumdesign.service.RentService;

import java.util.Objects;

public class ParkingDetailActivity extends AppCompatActivity {
    private TextView tvNumber,tvParkLotName,tvPrice,tvStatus,tvLocation,tvType;
    private ImageView btnBack;
    private Button button;
    private ParkingSpaceService parkingSpaceService;
    private OrderService orderService;
    private RentService rentService;
    private ParkLotService parkLotService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_detail);
        SharedPreferences optionParkLot = this.getSharedPreferences("optionParkLot", Context.MODE_PRIVATE);
        SharedPreferences loginInfo = this.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        parkingSpaceService = new ParkingSpaceService(this);
        orderService = new OrderService(this);
        rentService = new RentService(this);
        parkLotService = new ParkLotService(this);

        button = findViewById(R.id.btnAction);
        tvNumber = findViewById(R.id.tvNumber);
        tvParkLotName = findViewById(R.id.tvParkLotName);
        tvPrice = findViewById(R.id.tvPrice);
        tvStatus = findViewById(R.id.tvStatus);
        tvLocation = findViewById(R.id.tvLocation);
        tvType = findViewById(R.id.tvType);
        btnBack = findViewById(R.id.btnBack);

        // 获取传过来的数据
        Intent intent = getIntent();
        if (intent == null) {
            Toast.makeText(this, "系统错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        Long id = intent.getLongExtra("id", -1L);
        boolean status = intent.getBooleanExtra("parkLotStatus",false);
        Log.d("停车位","查看车位时选择的停车场状态"+status);
        ParkingSpace parkingSpace = parkingSpaceService.getParkingSpaceById(id);

        if (parkingSpace == null || optionParkLot.getString("parkOption"," ").equals(" ")) {
            Toast.makeText(this, "加载失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        tvNumber.setText(parkingSpace.getParkingSpaceNumber());
        tvParkLotName.setText(optionParkLot.getString("parkOption"," "));
        tvPrice.setText("￥ "+parkingSpace.getPricePerHours()+" /小时");
        tvStatus.setText(parkingSpace.getStatus() ? "空闲" : "占用");
        tvType.setText(TransitionUtils.transParkType(parkingSpace.getType()));
        if (parkingSpace.getStatus()) {
            tvStatus.setTextColor(Color.GREEN);  // 绿色
        } else {
            tvStatus.setTextColor(Color.RED);    // 红色
        }
        tvLocation.setText(parkingSpace.getLocation());

        btnBack.setOnClickListener(v -> finish());

        Log.d("测试","ParkDetailA登陆状态"+loginInfo.getBoolean("login",false));
        if (!loginInfo.getBoolean("login",false) || !parkingSpace.getStatus() || !status) {        //登陆验证
            Log.d("测试","租借/预约按键不加载");
            button.setVisibility(GONE);
        } else {
            button.setText("租借");
        }
        button.setOnClickListener(v -> {
            btnRent(parkingSpace);
        });
    }

    private void btnRent(ParkingSpace parkingSpace) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_rent, null);
        EditText etPlateNumber = dialogView.findViewById(R.id.etPlateNumber);

        AlertDialog dialogHolder = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setPositiveButton("确认", null)
                .setNegativeButton("取消", null)
                .create();
        dialogHolder.setOnShowListener(dlg -> {
            Button positiveBtn = dialogHolder.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveBtn.setOnClickListener(v -> {
                String plateNumber = etPlateNumber.getText().toString();                   //检测车牌
                    if (!Checker.isValidPlate(plateNumber)) {
                        Toast.makeText(this, "车牌格式错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                SharedPreferences loginInfo = this.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
                SharedPreferences optionParkLot = this.getSharedPreferences("optionParkLot", Context.MODE_PRIVATE);

                Long Uid = loginInfo.getLong("user_id",-1L);

                RentedParkingSpace rentedParkingSpace = new RentedParkingSpace();
                rentedParkingSpace.setLocation(parkingSpace.getLocation());
                rentedParkingSpace.setParkingSpaceNumber(parkingSpace.getParkingSpaceNumber());
                rentedParkingSpace.setParkingSpaceId(parkingSpace.getId());
                rentedParkingSpace.setParkLotId(parkingSpace.getParkLotId());
                rentedParkingSpace.setLicencePlate(plateNumber);
                rentedParkingSpace.setStartTime(TimeConverters.getNewTime());
                rentedParkingSpace.setType(parkingSpace.getType());
                rentedParkingSpace.setUserId(Uid);
                rentedParkingSpace.setParkLotName(optionParkLot.getString("parkOption"," "));

                Order order = new Order();
                    order.initializeByRent(rentedParkingSpace);
                    order.setEndTime(0L);
                    order.setTotalPrice(0.0);
                    order.setOrderNumber(GetUtils.generateOrderNumber());
                    order.setTransactionStatus(false);
                    order.setEndTime(0L);

                    parkingSpace.setStatus(false);
                    parkingSpaceService.update(parkingSpace);
                    long insert = orderService.insert(order);
                    rentedParkingSpace.setOrderId(insert);
                    long orderId = rentService.insert(rentedParkingSpace);

                    ParkLot parkLotById = parkLotService.getParkLotById(parkingSpace.getParkLotId());
                    parkLotById.setAvailableSpaces(parkLotById.getAvailableSpaces()-1);
                    parkLotService.update(parkLotById);

                    Toast.makeText(this, "租界成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(this, MyRentDetailActivity.class);
                    intent.putExtra("id", orderId);
                    intent.putExtra("rent",true);
                    finish();
                    this.startActivity(intent);
            });
        });

        Objects.requireNonNull(dialogHolder.getWindow()).setBackgroundDrawableResource(R.drawable.rounded_dialog_bg);//加弧角
        dialogHolder.show();
    }

}